<?php
/**
 * User:chendenan
 * Created On 2022/3/22 0022 21:18
 */
namespace app\common\business;
use think\facade\Cache;
use app\common\lib\{Key as KeyLib,Arr as ArrLib};
class Cart extends BusBase{
    /**
     * 添加购物车
     * @param $userId
     * @param $id
     * @param $num
     * @return array|false
     */
    public function insertRedis($userId,$id,$num){
        //ID获取商品数据
        $goodsSku = (new GoodsSku())->getSkuAndGoods($id);
        if(!$goodsSku){
            return FALSE;
        }
        $data = [
            "title" => $goodsSku['goods']['title'],
            "image" => $goodsSku['goods']['recommend_image'],
            "num"  => $num,
            "goods_id" => $goodsSku['goods']['id'],
            "create_time" => time(),
        ];
        try{
            $get = Cache::hGet(KeyLib::userCart($userId),$id);
            if($get){
                $get = json_decode($get,true);
                $data['num'] = $data['num'] + $get['num'];
                if($data['num'] > $goodsSku['stock']){
                    throw new \think\Exception($data['title']."的商品库存不足");
                }
            }
            $res[] = Cache::hSet(KeyLib::userCart($userId),$id,json_encode($data));
            if(in_array(false,array_count_values($res))){
                return [];
            }
        }catch(\Exception $e){
            trace($e->getMessage(),"error");
            return FALSE;
        }
        return $res;
    }

    /**
     * 查询购物车列表
     * @param $userId
     * @param $ids
     * @return array
     * @throws \think\Exception
     */
    public function lists($userId,$ids){
        try{
            if($ids){
                $ids = explode(",",$ids);
                $res = Cache::hMget(KeyLib::userCart($userId),$ids);
            }else{
                $res = Cache::hGetAll(KeyLib::userCart($userId));
            }
        }catch (\Exception $e){
            $res = [];
        }
        if(!$res){
            return [];
        }
        $result = [];
        $skuIds = array_keys($res);
        $skus = (new GoodsSku())->getInIds($skuIds);
        $stocks = array_column($skus,"stock","id");
        $skuIdPrice = array_column($skus,"price","id");
        $skuIdSpecsValueIds = array_column($skus,"specs_value_ids","id");
        $specsValues = (new SpecsValue())->detailSpecsValue($skuIdSpecsValueIds);
        foreach($res as $k=>$v){
            $price = $skuIdPrice[$k] ?? 0;
            $v = json_decode($v,true);
            //订单确认和提交订单 判断库存
            //如果当前库存小于提交数量 抛出异常
            if($ids && isset($stocks[$k]) && $stocks[$k] < $v['num']){
                throw new \think\Exception($v['title']."的商品库存不足");
            }
            $v['id'] = $k;
            $v['image'] = preg_match("/http:\/\//",$v['image'])?$v['image']:request()->domain().$v['image'];
            $v['price'] = $price;
            $v['total_price'] = $price * $v['num'];
            $v['sku'] = $specsValues[$k] ?? "暂无规则";
            $result[] = $v;
        }
        if(!empty($result)){
            ArrLib::arrSortByKey($result,"create_time");
        }
        return $result;
    }

    /**
     * 更新购物车某一商品的数量
     * @param $userId
     * @param $id
     * @param $num
     * @return false
     * @throws \think\Exception
     */
    public function updateRedis($userId,$id,$num){
        try{
            $get = Cache::hGet(KeyLib::userCart($userId),$id);
        } catch ( \Exception $e){
            return FALSE;
        }
        if($get){
            $get = json_decode($get,true);
            $get['num'] = $num;
        }else{
            throw new \think\Exception("不存在该购物车的商品，您更新没有任何意义");
        }
        try {
            $res = Cache::hSet(KeyLib::userCart($userId),$id,json_encode($get));
        } catch (\Exception $e){
            return FALSE;
        }
        return $res;
    }

    /**
     * 删除购物车
     * @param $userId
     * @param $id
     * @return false
     */
    public function deleteRedis($userId,$id){
        try {
//            //删除多个 或 一个 foreach 遍历方式
//            if(stristr($id,',')!==false){
//                $id = explode(',',$id);
//            }
//            if(is_array($id)){
//                foreach ($id as $v){
//                    $res = Cache::hDel(KeyLib::userCart($userId),$v);
//                }
//            }else{
//                $res = Cache::hDel(KeyLib::userCart($userId),$id);
//            }
            if(!is_array($id)){
                $ids = explode(",",$id);
            }
            // ... 是PHP提供一个特性 可变参数
            $res = Cache::hDel(KeyLib::userCart($userId),...$ids);
        } catch (\Exception $e){
            return FALSE;
        }
        return $res;
    }

    /**
     * 获取购物车数据
     * @param $userId
     * @return int|void
     */
    public function getCart($userId){
        try {
            $count = Cache::hLen(KeyLib::userCart($userId));
        } catch (\Exception $e){
            return 0;
        }
        return intval($count);
    }
}